﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SimpleORM
{
    public class UpdateTranslator : LambdaTranslator
    {
        #region Properties

        #endregion

        #region Methods

        #region Methods - Public

        public override void Translate(Expression expression)
        {
            MethodCallExpression m = expression as MethodCallExpression;
            Translate((m.Arguments[1] as ConstantExpression).Value, m);
        }

        public void Translate(object obj, MethodCallExpression m)
        {
            IScriptFactory f = DataSource.CreateScriptFactory();

            ObjectContext ocv = ObjectContextDictionary.Get(obj.GetType());
            ObjectContext oct = ocv.IsAnonymousClass ? ObjectContextDictionary.Get(((
                m.FindFirst().Arguments[0] as ConstantExpression).Value as IQueryable).ElementType) : ocv;

            IScriptFactory target = f.SchemaObject(oct.Schema, oct.TableName);
            var list = new List<DParameter>();

            foreach (var item in ocv.Columns)
            {
                if (item.Value.DataColumn.Auto)
                    continue;

                object value = item.Value.PropertyInfo.GetValue(obj, null);
                list.Add(f.CreateParameter(oct.Columns[item.Key].DataColumn.ColumnName, value));
            }

            Result = f.Update(target, list.ToArray());

        }

        #endregion

        #endregion
    }
}
